package server;

import server.mapper.Context;
import server.mapper.Host;
import server.mapper.Mapper;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author zyy
 * @date 2020/12/29 上午8:50
 * @description
 */
public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取静态资源输出流 通过输出流输出
     *
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count;
        //输出HTTP请求头 然后在输出具体内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //读取内容输出
        //已经读取的字节长度
        long written = 0;
        //计划每次读取的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            if (written + byteSize > resourceSize) {
                //说明剩余读取不足一个1024长度 那就按实际长度处理
                bytes = new byte[(int) (resourceSize - written)];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }

    }

    /**
     * 根据url和映射实体获取上下文对象
     * @param urlArr
     * @param mapper
     * @return
     */
    public static Context getContext(String[] urlArr, Mapper mapper){
        if(mapper.getHosts() == null || mapper.getHosts().isEmpty()) {
            return null;
        }

        for (Host host : mapper.getHosts()) {
            if(host.getName().equals(urlArr[0])){
                //匹配请求路径中的项目名称demo1和context，并返回
                if (host.getContexts() == null || host.getContexts().isEmpty()) {
                    return null;
                }
                for (Context context : host.getContexts()) {
                    if(context.getPath().equals(urlArr[1])){
                        return context;
                    }
                }
            }
        }
        return null;
    }
}
